﻿using Microsoft.EntityFrameworkCore;
using RepositoryDemo.Domain.Orders;
using RepositoryDemo.Domain.Orders.Repositories;
using RepositoryDemo.Infrastructure.EfCore;

namespace RepositoryDemo.Infrastructure.Repositories;

public class OrderRepository : IOrderRepository
{
    private readonly AppDbContext _dbContext;

    public OrderRepository(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<Order> GetAsync(int id)
    {
        return await _dbContext.Orders.AsNoTracking().FirstAsync(o => o.Id == id);
    }

    public async Task<List<Order>> GetListAsync()
    {
        return await _dbContext.Orders.AsNoTracking().ToListAsync();
    }

    public async Task<Order> InsertAsync(Order order)
    {
        await _dbContext.Orders.AddAsync(order);
        await _dbContext.SaveChangesAsync();
        return order;
    }

    public async Task<Order> UpdateAsync(Order order)
    {
        _dbContext.Update(order);
        await _dbContext.SaveChangesAsync();
        return order;
    }

    public async Task DeleteAsync(int id)
    {
        var order = await GetAsync(id);
        _dbContext.Orders.Remove(order);
        await _dbContext.SaveChangesAsync();
    }
}
